package com.cloud.config;

import com.cloud.domain.LoginUser;
import com.cloud.pojo.SysLog;
import com.cloud.service.SysLogService;
import com.cloud.utils.MyTime;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @Author: Tangtao
 * @Date: 2022/5/12 9:09
 * @Description:
 * @ClassName:
 */
@Aspect
@Component
public class LogAspect {
    @Resource
    private SysLogService sysLogService;

    //表示匹配带有自定义注解的方法
    @Pointcut("@annotation(com.cloud.config.Log)")
    public void pointcut() {}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result =null;
        long beginTime = System.currentTimeMillis();

        try {
            result = point.proceed();
            long endTime = System.currentTimeMillis();
            insertLog(point,endTime-beginTime);
        } catch (Throwable e) {
            // TODO Auto-generated catch block
        }
        return result;
    }

    private void insertLog(ProceedingJoinPoint point ,long time) {
        MethodSignature signature = (MethodSignature)point.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = new SysLog();

        Log userAction = method.getAnnotation(Log.class);
        if (userAction != null) {
            // 注解上的描述
            sysLog.setUserAction(userAction.value());
        }

        // 请求的类名
        String className = point.getTarget().getClass().getName();
        // 请求的方法名
        String methodName = signature.getName();
        // 请求的方法参数值
        String args = Arrays.toString(point.getArgs());

        //从session中获取当前登陆人id
//        Long useride = (Long)SecurityUtils.getSubject().getSession().getAttribute("userid");

        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userid = loginUser.getUser().getUserId();

        sysLog.setUserId(userid);

        sysLog.setCreateTime(MyTime.getCurrTimeAsDate());

        System.out.println(loginUser.getUser());

        System.out.println(sysLog);
        int res = sysLogService.insertLog(sysLog);
        System.out.println(res);
    }
}
